package com.cat.mrli.rat;

import android.content.Context;
import android.opengl.GLSurfaceView;

import com.cat.mrli.rat.objects.Mallet;
import com.cat.mrli.rat.objects.Table;
import com.cat.mrli.rat.programs.ColorShaderProgram;
import com.cat.mrli.rat.programs.TextureShaderProgram;
import com.cat.mrli.rat.util.MatrixHelper;
import com.cat.mrli.rat.util.TextureHelper;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;
import static android.opengl.Matrix.multiplyMM;
import static android.opengl.Matrix.rotateM;
import static android.opengl.Matrix.setIdentityM;
import static android.opengl.Matrix.translateM;

/**
 * Created by MrLi on 2017/6/20.
 */

public class GLRenderer implements GLSurfaceView.Renderer {
    private final Context context;

    private final float[] projectMatrix = new float[16];
    private final float[] modelMatrix = new float[16];


    private Table table;
    private Mallet mallet;


    private TextureShaderProgram textureShaderProgram;
    private ColorShaderProgram colorShaderProgram;


    private int texture;
    private int texTure1;

    public GLRenderer(Context context) {
        this.context = context;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        glClearColor(0f, 0f, 0f, 0f);

        table = new Table();
        mallet = new Mallet();

        textureShaderProgram = new TextureShaderProgram(context);
        colorShaderProgram = new ColorShaderProgram(context);

        texture = TextureHelper.loadTexture(context, R.drawable.air_hockey_surface);
        texTure1 = TextureHelper.loadTexture(context, R.mipmap.ic_launcher);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        glViewport(0, 0, width, height);

        MatrixHelper.perspectiveM(projectMatrix, 45, (float) width / (float) height, 1f, 10f);

        setIdentityM(modelMatrix, 0);
        translateM(modelMatrix, 0, 0f, 0f, -2.5f);
        rotateM(modelMatrix, 0, -60f, 1f, 0f, 0f);

        final float[] temp = new float[16];
        multiplyMM(temp, 0, projectMatrix, 0, modelMatrix, 0);
        System.arraycopy(temp, 0, projectMatrix, 0, temp.length);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        glClear(GL_COLOR_BUFFER_BIT);

        textureShaderProgram.userProgram();
        textureShaderProgram.setUniforms(projectMatrix, texture, texTure1);
        table.bindData(textureShaderProgram);
        table.draw();

        colorShaderProgram.userProgram();
        colorShaderProgram.setUniforms(projectMatrix);
        mallet.bindData(colorShaderProgram);
        mallet.draw();
    }
}
